package com.b2c.erp.interceptor;
import com.b2c.erp.DataConfigObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import com.b2c.interfaces.WmsUserService;

import java.io.IOException;

/**
 * 默认拦截器
 */
@Component
public class InitInterceptor implements HandlerInterceptor {
    @Autowired
    private WmsUserService wmsUserService;
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws IOException {
        HttpSession session = request.getSession();
        String url=request.getRequestURI();
        //String queryurl=request.getQueryString();
        //if(null!=queryurl)url+="?"+queryurl;
//        System.out.println("请求拦截，USERID"+session.getAttribute("userId"));
        String targetUrl = request.getRequestURL().toString();
        if (StringUtils.isEmpty(request.getQueryString()) == false) {
            targetUrl += "?" + request.getQueryString();
        }

//        if (StringUtils.isEmpty(session.getAttribute("userId"))) {
//            System.out.println("请求拦截，没有登录调整到登录页面");
//            response.sendRedirect(request.getContextPath() + "/login?ref=" + targetUrl);
//        }

        try {
            //判断权限，(int) session.getAttribute("userId")
            Integer userId = DataConfigObject.getInstance().getLoginUserId();
            boolean flag = wmsUserService.checkUserPermissionMenuByUrl(userId, url);
            if (flag == false) {
                System.out.println("请求拦截"+url+"，没有权限："+userId);
                redirect(request, response);
                //response.sendRedirect(request.getContextPath() + "/no_access");
                return false;
            }
        }catch (Exception e){
            System.out.println("请求拦截异常："+e.getMessage());
//            System.out.println("跳转到登录页面");
//            redirect(request, response);
            response.sendRedirect(request.getContextPath() + "/login?ref=" + targetUrl);
            return false;
        }
        return true;
    }

    //对于请求是ajax请求重定向问题的处理方法
    public void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //获取当前请求的路径
        String basePath = request.getScheme() + "://" + request.getServerName() + ":"  + request.getServerPort()+request.getContextPath();
        if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
            //告诉ajax请求是重定向
            response.setHeader("REDIRECT", "NO_ACCESS");
            //response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }else{
            response.sendRedirect(basePath + "/no_access");
        }
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object object, ModelAndView mv)
            throws Exception {
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行
     * （主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object object, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }
}
